--
-- Author: yu.yu
-- Date: 2018-11-13 10:30:50
--
-- LotteryDropPanel

local IconRender = require("app.widget.renders.IconRender")

local ClassRef = app.mvc.createPanelClass(...)

local EACH_ROW_NUM = 5 --每行的icon个数
local ITEM_OFFX = 2 --item水平方向间距
local ITEM_OFFY = 2 --item垂直方向间距

function ClassRef.create(node)
    local sprite = ClassRef.extend(node or cc.CSLoader:createNode(Res.LotteryDropPanel))
    if node == nil then
        ccui.Helper:doLayout(sprite)
    end
    sprite:init()
    return sprite
end

function ClassRef:init(data)
    self.super.init(self, data)
end

function ClassRef:refresh()
    if self._data then
        self._ui["Panel"]:setTouchEnabled(false)
        local originalHeight = self._ui["Panel"]:getContentSize().height
        -- name
        local nameNode = self._ui["Panel/bg/name"]
        local name = self._data.name
        nameNode:setString(L(name))

        -- item     
        local iconParent = self._ui["Panel/iconParent"]
        local itemList = UD:parseItemsFromString(self._data.dropList, UD:getClass())
        local panelHeight = 0
        local tempWidth = 0
        local itemWidth, itemHeight
        for i, data in ipairs(itemList) do
            local item = IconRender.create()
            item:setData(data)
            item:setTipEnable(true)
            item:setTipUnShowOrigin(true)
            item:setAnchorPoint(cc.p(0,1))
            item:setTipsCloseCallBack(function(tp)
                if self._tipsCloseCalllback then
                    self._tipsCloseCalllback(tp)
                end
            end)
            iconParent:addChild(item)
            
            if not itemWidth then
                itemWidth = item:getContentSize().width + ITEM_OFFX
                itemHeight = item:getContentSize().height + ITEM_OFFY
            end

            local curRow = math.floor((i-1) / EACH_ROW_NUM) 
            if ((i-1) % EACH_ROW_NUM) == 0 then
                tempWidth = 0
                panelHeight = curRow * itemHeight
            end
            item:setPosition(cc.p(tempWidth, -panelHeight))
            tempWidth = tempWidth + itemWidth
        end

        panelHeight = panelHeight + itemHeight - ITEM_OFFY
        iconParent:setPositionY(panelHeight)
        self._ui["Panel/bg"]:setPositionY( self._ui["Panel/bg"]:getPositionY() + panelHeight)
        local nameHeight = self._ui["Panel/bg"]:getContentSize().height
        local width = self:getContentSize().width
        self:setContentSize(width, originalHeight+panelHeight)
    end
end

function ClassRef:setTipsCloseCallBack(f)
	self._tipsCloseCalllback = f
end

return ClassRef